Kurs Java (11)
Spis tematów
1. Język Java
1.1. Elementarny program: tekst źródłowy, kompilacja, interpretacja
1.2. Klasy: definicja, dziedziczenie, tworzenie obiektów
1.3. Interfejsy
1.4. Pliki źródłowe i pakiety
1.5. Polimorfizm
1.6. Obsługa wyjątków
1.7. Zarządzanie pamięcią
1.8. Współbieżność
1.8.1 Synchronizacja wątków
1.9. Obiekty sieciowe
2. Aplety - programy Javy na stronach WWW
3. Standardowe klasy Javy
4. Servlety - programy Javy na serwerze WWW
5. Podsumowanie
6. Programy - ćwiczenia
/czcionką pogrubioną zaznaczono tematy zawarte w tej części/
6. Programy - ćwiczenia
Plik Squares.java
class Squares {
/** Print out the squares of integers from 1 to 10 */
public static void main(String[] args) {
int x = 1;
System.out.println("Squares of integers from 1 to 10:");
while (x <= 10) {
System.out.println(x * x); // print x squared
x = x + 1; // add 1 to x
}
}
}
Plik StringDemo.java
class StringsDemo {
static public void main(String[] args) {
String myName = "Archibald";
myName = myName + " Tuttle";
System.out.println("Name = " + myName);
}
}
Plik PascalTriangle.java
import java.io.*;
public class PascalTriangle {
private int data[][];
/** Create a Pascal's triangle to specified depth. */
public PascalTriangle(int rows) {
data = new int[rows][];
for (int row = 0; row < rows; row++) {
data[row] = new int[row + 1];
if (row == 0)
data[row][0] = 1;
else
for (int col = 0; col <= row; col++) {
data[row][col] = 0;
// if not on right edge, add node up and right
if (col < row)
data[row][col] += data[row - 1][col];
// if not on left edge, add node up and left
if (col > 0)
data[row][col] += data[row - 1][col - 1];
}
}
}
/** Print this Pascal's triangle to given stream. */
public void print(PrintStream ps) {
for (int i = 0; i < data.length; i++) {
int[] row = data[i];
for (int j = 0; j < row.length; j++)
ps.print(row[j] + " ");
ps.println();
}
}
/** Create a Pascal's triangle of depth 12 and print it. */
public static void main(String[] args)
{
PascalTriangle pt = new PascalTriangle(12);
pt.print(System.out);
}
}
Plik EasyIn.java
// Simple input from the keyboard for all primitive types. ver 1.0
// Not thread safe, not high performance, and doesn't tell EOF.
// It's intended for low-volume easy keyboard input.
// An example of use is:
// EasyIn easy = new EasyIn();
// int i = easy.readInt(); // reads an int from System.in
// float f = easy.readFloat(); // reads a float from System.in
import java.io.*;
import java.util.*;
class EasyIn {
static InputStreamReader is = new InputStreamReader( System.in );
static BufferedReader br = new BufferedReader( is );
StringTokenizer st;
StringTokenizer getToken() throws IOException {
String s = br.readLine();
return new StringTokenizer(s);
}
boolean readBoolean() {
try {
st = getToken();
return new Boolean(st.nextToken()).booleanValue();
} catch (IOException ioe) {
System.err.println("IO Exception in EasyIn.readBoolean");
return false;
}
}
byte readByte() {
try {
st = getToken();
return Byte.parseByte(st.nextToken());
} catch (IOException ioe) {
System.err.println("IO Exception in EasyIn.readByte");
return 0;
}
}
short readShort() {
try {
st = getToken();
return Short.parseShort(st.nextToken());
} catch (IOException ioe) {
System.err.println("IO Exception in EasyIn.readShort");
return 0;
}
}
int readInt() {
try {
st = getToken();
return Integer.parseInt(st.nextToken());
} catch (IOException ioe) {
System.err.println("IO Exception in EasyIn.readInt");
return 0;
}
}
long readLong() {
try {
st = getToken();
return Long.parseLong(st.nextToken());
} catch (IOException ioe) {
System.err.println("IO Exception in EasyIn.readLong");
return 0L;
}
}
float readFloat() {
try {
st = getToken();
return new Float(st.nextToken()).floatValue();
} catch (IOException ioe) {
System.err.println("IO Exception in EasyIn.readFloat");
return 0.0F;
}
}
double readDouble() {
try {
st = getToken();
return new Double(st.nextToken()).doubleValue();
} catch (IOException ioe) {
System.err.println("IO Exception in EasyIn.readDouble");
return 0.0;
}
}
char readChar() {
try {
String s = br.readLine();
return s.charAt(0);
} catch (IOException ioe) {
System.err.println("IO Exception in EasyIn.readChar");
return 0;
}
}
String readString() {
try {
return br.readLine();
} catch (IOException ioe) {
System.err.println("IO Exception in EasyIn.readString");
return "";
}
}
// This method is just here to test the class
public static void main (String args[]){
EasyIn easy = new EasyIn();
System.out.print("enter char: "); System.out.flush();
System.out.println("You entered: " + easy.readChar() );
System.out.print("enter String: "); System.out.flush();
System.out.println("You entered: " + easy.readString() );
System.out.print("enter boolean: "); System.out.flush();
System.out.println("You entered: " + easy.readBoolean() );
System.out.print("enter byte: "); System.out.flush();
System.out.println("You entered: " + easy.readByte() );
System.out.print("enter short: "); System.out.flush();
System.out.println("You entered: " + easy.readShort() );
System.out.print("enter int: "); System.out.flush();
System.out.println("You entered: " + easy.readInt() );
System.out.print("enter long: "); System.out.flush();
System.out.println("You entered: " + easy.readLong() );
System.out.print("enter float: "); System.out.flush();
System.out.println("You entered: " + easy.readFloat() );
System.out.print("enter double: "); System.out.flush();
System.out.println("You entered: " + easy.readDouble() );
}
}
Plik Heritage.java
/**Program krotko demonstruje mechanizm korzystania z interfejsow*/
/**Glowna klasa programu, tworzy pozostale*/
public class Heritage
{
public static void main (String[] args) {
/*tworzymy obiekty i wywolujemy odpowiednie metody*/
Client our_client = new Client();
our_client.startingReport();
Server our_server= new Server (our_client);
our_server.execute(5);
}
}
/**Klasa klienta implementuje interfejs Message*/
class Client implements Message {
int counter=0;
/**zeruje licznik i wyswietla komunikat poczatkowy*/
public void startingReport()
{
counter=0;
System.out.println ("To jest raport poczatkowy klienta");
System.out.println ("Counter="+counter);
}
/**Zwieksza licznik i wyswietla jego wartosc - podajac, ze klasa
implementuje interfejs Message; zobowiazalismy sie, ze metoda o nazwie
giveReport bedzie istniala*/
public void giveReport()
{
counter++;
System.out.println ("Counter="+counter);
}
}
/**Klasa serwera korzysta z obiektu majacego zaimplementowany interfejs
Message*/
class Server
{
/*Zwrocmy uwage, ze typem obiektu jest nazwa interfejsu*/
Message object;
/**Konstuktor. Jako parametr podajemy dowolny obiekt majacy
zaimplementowany interfejs Message; w naszym przypadku bedzie to Client*/
Server (Message object)
{
this.object=object;
}
/** Wywolujemy metode giveReport obiektu z interfejsem Message times razy
*/
public void execute (int times)
{
for (int k=0; k<times; k++)
object.giveReport();
}
}
/**Interfejs Message, kazda klasa ktora go zaimplementuje musi posiadac
metode giveReport*/
interface Message
{
/**Tylko zobowiazanie, ze kazda klasa ktora implementuje ten interfejs
bedzie miala metode giveReport - jej dzialanie bedzie zalezec od danej klasy*/
void giveReport();
}
Plik Compare.java
/**Program krotko demonstruje mechanizm wyjatkow w Java*/
import java.io.*;
/**Klasa porownuje dwa pliki i zwraca rezultat porowanania na ekranie*/
public class Compare {
/**glowna i jedyna metoda aplikacji*/
public static void main (String[] args) {
/*nazwy plikow*/
String first_file = args[0];
String second_file = args[1];
/*obiekty reprezentujace pliki*/
RandomAccessFile first =null;
RandomAccessFile second =null;
/*Zawartosc plikow bedzie umieszczona w tych buforach*/
byte[] first_buffer;
byte[] second_buffer;
/*Dlugosci plikow*/
int first_size = -1;
int second_size = -1;
try {
System.out.println ("Ten program porowna dwa pliki");
System.out.println ("plik 1: "+first_file+" plik2: "+second_file);
try {
first = new RandomAccessFile(first_file, "r");
second = new RandomAccessFile(second_file, "r");
/*blok, w ktorym porownujemy*/
prawie_koniec:{ //etykieta
first_size = (int)first.length();
second_size = (int)second.length();
/*najpierw porownujemy dlugosci*/
if (first_size!=second_size)
{
System.out.println ("Rozne pliki");
break prawie_koniec;
}
/*jesli dlugosci identyczne, wczytujemy pliki do pamieci*/
first_buffer = new byte [first_size];
second_buffer = new byte [second_size];
first.readFully (first_buffer, 0, first_size);
second.readFully (second_buffer, 0, second_size);
/*porownujemy zawartosc plikow*/
for (int i=0; i<first_size; i++)
{
if (first_buffer[i]!=second_buffer[i])
{
System.out.println ("Rozne pliki");
break prawie_koniec;
}
}
System.out.println ("Pliki identyczne");
}
/*tutaj przechodzi break prawie_koniec*/
System.out.println ("---------------");
}
/*przechwytujemy wyjatki zwiazane z operacjami I/O*/
catch (IOException e)
{
System.out.println ("Blad I/O");
}
/*to sie zawsze wykona*/
finally
{
try
{
first.close();
second.close();
}
/*podczas zamykania plikow ignorujemy wyjatki*/
catch (Exception ignored) { }
System.out.println ("Koniec czesci wewnetrznej");
}
}
/*tu przechwytujemy wyjatki nie obsluzone w czesci wewnetrznej*/
catch (Exception e)
{
System.out.println ("Wystapil nastepujacy wyjatek przechwycony w main");
System.out.println (e);
System.out.println ("Uzycie programu: Compare pierwszy_plik drugi_plik");
}
/*na koniec zawsze wyswietlamy krotki komunikat*/
finally
{
System.out.println ("Koniec dzialania programu");
}
} //end main
}// end Compare
Bibliografia
[1] Cargill T. An Overview of Java for C++ Programmers. C++ Report, vo. 8,
No. 2, pp. 46-49, 1996.
[2] Lorenz M. Java as an Object-Oriented Language. SIGS Books & Multimedia, New
York 1996.
[3] Martin R. C++ and Java: A Critical Comparison. C++ Report, vo. 9, No. 1, pp.
42-49, 1997.
[4] Jain P. and Schmidt D.C. Experiences Converting a C++ Communication Software
Framework to Java. C++ Report, vo. 9, No. 1, pp. 51-66, 1997.
[5] Gosling J., Joy B, Steele G. The Java Language Specification. Addison-Wesley,
1996, http://java.sun.com/docs/books/jls/.
[6] The Java Tutorial. http://java.sun.com/docs/books/tutorial/, 1998.
[7] JDK1.1.6 Documentation. http://java.sun.com/products/jdk/1.1/docs/, 1998.
[8] Servlet Tutorial. http://www.task.gda.pl/java/ServletTutorial.html, 1998.
Kurs pochodzi ze strony:
Java Kurs
Dla magazynu @t opracował:
Dariusz Frankowski
|